package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.RetailInAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.OrderQueryParams;
import com.isunland.managesystem.entity.RInappMain;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  零购入库列表
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/7/18 14:06
 */
public class RetailInListFragment extends BaseListFragment {

  private ArrayList<RInappMain> mlist;
  private int REQUEST_QUERY = 1;

  private String minkindCode;
  private OrderQueryParams mQueryParams;
  private String minbillno;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom("零购入库");
    //获取单据编号
    volleyGetCode();
  }

  @Override public void initData() {
    mlist = new ArrayList<>();
    minkindCode = MyStringUtil.connect(mCurrentUser.getMemberCode(), "-DJLB-IN-LGRK");
    mQueryParams = new OrderQueryParams();
    mQueryParams.setBeginregDate(
        MyDateUtil.format(MyDateUtil.getBeforeMonth(1), MyDateUtil.TYPE_DATE));
    mQueryParams.setEndregDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
    mQueryParams.setDataStatusName(getString(R.string.all));
    mQueryParams.setFrom(RetailInQueryFragment.RETAIL_IN);//入库和出库使用同一个查询界面: 来自入库
    mBaseParams = new BaseParams();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_delegatetask, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

      case R.id.menu_item_add:
        //默认值
        RInappMain content = new RInappMain();
        content.setId(UUID.randomUUID().toString());
        content.setMindealDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
        content.setMinkindCode(minkindCode);//类型code
        content.setMinkindName("零购入库");//类型name
        content.setMinbillno(minbillno);//出库单编号
        content.setMinappmanName(mCurrentUser.getRealName());//申办人name
        content.setMinappmanId(mCurrentUser.getJobNumber());//申办人job
        content.setMinappmanDeptName(mCurrentUser.getDeptName());//申办人部门
        content.setMinappmanDeptCode(mCurrentUser.getDeptCode());//申办人部门code
        content.setMinappDate((MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE)));//申办时间
        content.setMinbillStatusCode(DataStatus.NEW);//数据状态
        content.setMinbillStatusName(DataStatus.getDataStatusName(DataStatus.NEW));//数据状态
        content.setRegStaffName(mCurrentUser.getRealName());//登记人
        content.setRegStaffId(mCurrentUser.getJobNumber());
        content.setRegDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));//登记时间
        mBaseParams.setItem(content);
        mBaseParams.setType(BaseParams.TYPE_ADD);
        RetailInDetailActivity.newInstance(this, RetailInDetailActivity.class, mBaseParams, 0);
        return true;
      case R.id.menu_item_search1:
        BaseVolleyActivity.newInstance(this, RetailInQueryActivity.class, mQueryParams,
            REQUEST_QUERY);
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public String getUrl() {
    return ApiConst.URL_RETAIL_IN_MIAN_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("regStaffId", mCurrentUser.getJobNumber());
    params.put("beginminappDate", mQueryParams.getBeginregDate());
    params.put("endminappDate", mQueryParams.getEndregDate());
    params.put("minbillStatusCode", mQueryParams.getDataStatus());
    params.put("minkindCode", minkindCode);
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    BaseOriginal<RInappMain> original =
        new Gson().fromJson(json, new TypeToken<BaseOriginal<RInappMain>>() {
        }.getType());
    if (Base.SUCCESS == original.getResult() && original.getRows() != null) {
      mlist.clear();
      mlist.addAll(original.getRows());
      RetailInAdapter madapter = new RetailInAdapter(mActivity, mlist);
      setListAdapter(madapter);
    } else {
      ToastUtil.show("获取列表失败");
    }
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    RInappMain inMain = mlist.get(position - 1);
    mBaseParams.setItem(inMain);
    mBaseParams.setType(BaseParams.TYPE_DETAIL);//详情
    RetailInDetailActivity.newInstance(this, RetailInDetailActivity.class, mBaseParams, 0);
  }

  //获取单据编号
  private void volleyGetCode() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_IN_BILL);
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("ruleFlag", "outReceiptsRecordCode");
    params.put("certificateCode", minkindCode);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            //获取单据编号成功
            minbillno = success.getMessage();
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    //查询
    if (requestCode == REQUEST_QUERY) {
      mQueryParams = (OrderQueryParams) data.getSerializableExtra(BaseQueryFragment.EXTRA_PARAMS);
    }
    volleyPost();
    super.onActivityResult(requestCode, resultCode, data);
  }
}
